package com.millstein.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.millstein.realtime.app.base.BaseAppV1;
import com.millstein.realtime.bean.UserRegisterBean;
import com.millstein.realtime.common.Constants;
import com.millstein.realtime.util.CommonUtil;
import com.millstein.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_05_UserUserRegisterWindow extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws_05_UserUserRegisterWindow().init(
                8005,
                3,
                "Dws_05_UserUserRegisterWindow",
                Constants.TOPIC_DWD_USER_REGISTER
        );
    }
    /**
     * 具体数据处理的逻辑，由子类编写
     *
     * @param env          执行环境对象
     * @param streamSource 待处理的数据流
     */
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> streamSource) {
        streamSource
                .map(new MapFunction<String, UserRegisterBean>() {
                    @Override
                    public UserRegisterBean map(String value) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(value);
                        return UserRegisterBean.builder()
                                .registerCt(1L)
                                .ts(jsonObject.getLong("ts") * 1000)
                                .build();
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserRegisterBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserRegisterBean>() {
                                    @Override
                                    public long extractTimestamp(UserRegisterBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<UserRegisterBean>() {
                            @Override
                            public UserRegisterBean reduce(UserRegisterBean value1,
                                                           UserRegisterBean value2
                            ) throws Exception {
                                value1.setRegisterCt(value1.getRegisterCt() + value2.getRegisterCt());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<UserRegisterBean, UserRegisterBean, TimeWindow>() {
                            @Override
                            public void process(Context context,
                                                Iterable<UserRegisterBean> elements,
                                                Collector<UserRegisterBean> out
                            ) throws Exception {
                                UserRegisterBean bean = elements.iterator().next();
                                String startTime = CommonUtil.formatTime(context.window().getStart());
                                String endTime = CommonUtil.formatTime(context.window().getEnd());
                                String curDate = startTime.substring(0, 10);
                                bean.setStt(startTime);
                                bean.setEdt(endTime);
                                bean.setCurDate(curDate);
                                out.collect(bean);
                            }
                        }
                )
                .map((MapFunction<UserRegisterBean, String>) value -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    return JSONObject.toJSONString(value, config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("gmall.dws_user_user_register_window"));
    }
}
